/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BigGUI.java
 *
 * Created on 31.01.2010, 12:58:43
 */

package net.q1cc.cfs.jamp;

import java.awt.dnd.DropTarget;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import net.q1cc.cfs.jamp.event.EventType;
import net.q1cc.cfs.jamp.event.JAmpEvent;
import net.q1cc.cfs.jamp.event.JAmpEventListener;
import net.q1cc.cfs.jamp.event.JAmpSongEvent;
import net.q1cc.cfs.jamp.players.PlayerHandler;
import net.q1cc.cfs.jamp.players.PlayerHandler.Status;
import net.q1cc.cfs.jamp.schema.Song;

/**
 *
 * @author claus
 */
public class BigGUI extends javax.swing.JFrame implements Runnable{

    Main main;
    DBHandler dbHandler;
    int firstClickedRow;
    long firstClickTime;
    Icon playIcon;
    Icon pauseIcon;
    boolean playing = false;
    DBImporter dBImporter;
    DropTarget dropTarget;
    SliderThread sliderThread;

    /** Creates new form BigGUI */
    public BigGUI() {
        main = Main.getInstance();
        this.dbHandler = main.dbHandler;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        duration = new javax.swing.JLabel();
        position = new javax.swing.JLabel();
        songtitle = new javax.swing.JLabel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        playLists = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        mainList = new javax.swing.JTable();
        playPauseButton = new javax.swing.JButton();
        jSlider1 = new javax.swing.JSlider();
        nextButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        shuffleCheck = new javax.swing.JCheckBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("Search");
        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField1MouseClicked(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        duration.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        duration.setText(" ");
        duration.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);

        position.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        position.setText(" ");
        position.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        songtitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        songtitle.setText(" ");
        songtitle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jSplitPane1.setDividerLocation(120);

        playLists.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(playLists);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jScrollPane2MouseClicked(evt);
            }
        });
        jScrollPane2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jScrollPane2MouseDragged(evt);
            }
        });

        mainList.setModel(dbHandler);
        mainList.setDragEnabled(true);
        mainList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(mainList);

        jSplitPane1.setRightComponent(jScrollPane2);

        playPauseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playPauseButtonActionPerformed(evt);
            }
        });

        jSlider1.setMajorTickSpacing(1000);
        jSlider1.setMaximum(100000);
        jSlider1.setMinorTickSpacing(100);
        jSlider1.setPaintTicks(true);
        jSlider1.setValue(0);
        jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jSlider1MousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jSlider1MouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jSlider1MouseClicked(evt);
            }
        });
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        nextButton.setText(">>");
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playNextSong(evt);
            }
        });

        jButton2.setText("<<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playPreviousSong(evt);
            }
        });

        shuffleCheck.setText("Shuffle");
        shuffleCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                shuffleAction(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Play / Pause");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem3.setText("Settings");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Library");

        jMenuItem2.setText("Read Database from iTunes");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 851, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playPauseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(1, 1, 1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(position, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                                .addGap(12, 12, 12)
                                .addComponent(duration, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(songtitle, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)))
                    .addComponent(shuffleCheck))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(duration, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(position, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                            .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(songtitle))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nextButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
                            .addComponent(playPauseButton, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(shuffleCheck))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mainListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainListMouseClicked
        //TODO doubleclick with position checking
        //TODO sorting the list
        //wie fange ich click events auf den spaltenbezeichnungen auf?

        if(evt.getButton()!=1)
            return;

        System.out.println("Column: "+mainList.columnAtPoint(evt.getPoint()));
        System.out.println("Klicked: "+evt.getPoint()+" Button: "+evt.getButton()+" Times: "+evt.getClickCount());

        if(evt.getClickCount()>1)
        {
            firstClickedRow=mainList.getSelectedRow();
            doubleClicked();
        }

        /*if (firstClickTime!=0
                && firstClickTime+100<=evt.getWhen())
        {
            firstClickTime=firstClickedRow=0;
            firstClickedRow=mainList.getSelectedRow();
            doubleClicked();

        } else {
            firstClickTime=evt.getWhen();
        }*/
    }//GEN-LAST:event_mainListMouseClicked

    SearchThread searchThread;
    long lastKeyPressed=0;
    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
        lastKeyPressed=System.currentTimeMillis();
        if(searchThread!=null && searchThread.isAlive())
        {
            return;
        }
        searchThread = new SearchThread();
        searchThread.start();
    }//GEN-LAST:event_jTextField1KeyTyped

    private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseClicked
        if(jTextField1.getText().equals("Search"))
            jTextField1.setText("");
    }//GEN-LAST:event_jTextField1MouseClicked

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        //Read DB
        Object[] options= {"Yes","No"};
        int n=JOptionPane.showOptionDialog(this,"DB import" +
                    "Do you really want to import your iTunes Library?\nThis will delete all your data in JAmp.","import",
                    JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,
            options,options[1]);
        if(n==0)//yes
            {
                File iTunesFolder;
                JFileChooser chooser = new JFileChooser();
                JOptionPane.showMessageDialog(
                        this, "Bitte wählen Sie jetzt die Datei iTunes Music Library(.xml) aus.\n" +
                        "Die Datei ist im iTunes Ordner in ihrem \"Eigene Musik\"-Ordner."
                        ,"iTunes-Ordner auswählen",JOptionPane.INFORMATION_MESSAGE);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setFileHidingEnabled(false);
                chooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    if (f.getName().equals("iTunes Music Library.xml"))
                        return true;
                    else if(f.isDirectory())
                        return true;
                    else
                        return false;
                }
                @Override
                public String getDescription() {
                    return "iTunes Music Library.xml";
                }
            });

                int returnVal = chooser.showOpenDialog(Main.getInstance().bigGUI);
                if(returnVal == JFileChooser.APPROVE_OPTION) {

                    iTunesFolder = chooser.getSelectedFile();

                } else
                    return;
            
            dBImporter = new DBImporter(dbHandler, iTunesFolder.getPath());
            
                
            Thread t = new Thread(){
                @Override
                public void run() {
                    readDB();
                }
            };
            t.setName("DBImporter");
            t.setPriority(Thread.MIN_PRIORITY);
            t.start();


            
            } else { //no
                //dann halt nicht.
            return;
            }
    }//GEN-LAST:event_jMenuItem2ActionPerformed
    /**
     * must set dBImporter first.
     *
     */
    private void readDB()
    {
        dBImporter.checkCreateTables();
        dBImporter.readiTunesToSQLDB();
        System.out.println("finished importing.");
    }
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        playPauseButtonActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        new SettingsDialog(this,false).setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void playPauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playPauseButtonActionPerformed
        if(dbHandler.currentSongRow==-1) //not playing
        {
            int selectedRow=mainList.getSelectedRow();
            if(selectedRow==-1) selectedRow=1;
            dbHandler.playSong(selectedRow);

        } else { //playing
            if(main.getPlayer().getStatus()==Status.PLAYING) {
                main.getPlayer().playpause();
                playPauseButtonPlaying(!playing);
            } else {
                main.getPlayer().playpause();
                playPauseButtonPlaying(!playing);
            }
        }
    }//GEN-LAST:event_playPauseButtonActionPerformed

    private void jScrollPane2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane2MouseClicked
        
    }//GEN-LAST:event_jScrollPane2MouseClicked

    private void jScrollPane2MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane2MouseDragged
        //delete this
    }//GEN-LAST:event_jScrollPane2MouseDragged
    
    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        
    }//GEN-LAST:event_jSlider1StateChanged
    
    private void jSlider1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MouseClicked
        
    }//GEN-LAST:event_jSlider1MouseClicked

    private void jSlider1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MouseReleased
        
        long time= jSlider1.getValue(); 
        mousePressedOnSlider1=false;
        main.getPlayer().seek(time*1000);
        System.out.println("skipped to time: "+time*1000);
    }//GEN-LAST:event_jSlider1MouseReleased

    private void playNextSong(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playNextSong
        dbHandler.nextSong();
    }//GEN-LAST:event_playNextSong

    private void playPreviousSong(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playPreviousSong
        dbHandler.previousSong();
    }//GEN-LAST:event_playPreviousSong

    private void shuffleAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_shuffleAction
        if(shuffleCheck.isSelected())
        {
            main.dbHandler.shuffle = true;
        }
        else 
        {
            main.dbHandler.shuffle = false;
        }
    }//GEN-LAST:event_shuffleAction
    boolean mousePressedOnSlider1;
private void jSlider1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSlider1MousePressed
    mousePressedOnSlider1=true;
}//GEN-LAST:event_jSlider1MousePressed


    private void doubleClicked()
    {
        System.out.println(mainList.getRowSorter().convertRowIndexToModel(firstClickedRow));
        dbHandler.playSong(mainList.getRowSorter().convertRowIndexToModel(firstClickedRow));
    }
    public void setCurrentSongRow(int row)
    {
        Song s= dbHandler.getSongAt(row);
        String text = " " + s.getValue("Name");
        if (s.getValue("Artist")!=null)
        {
            text = text + " - " + s.getValue("Artist");
        }
        if (s.getValue("Album")!=null)
        {
            text = text + " - " + s.getValue("Album");
        }
        songtitle.setText(text);
        playPauseButtonPlaying(true);
    }
    public void listEnded()
    {
        playPauseButtonPlaying(false);
        
        songtitle.setText("");
        position.setText("");
        duration.setText("");
    }
    public void playPauseButtonPlaying(boolean b)
    {
        if(b)
        {
            playPauseButton.setIcon(pauseIcon);
            playing=true;
        } else {
            playPauseButton.setIcon(playIcon);
            playing=false;
        }
    }

    private class SearchThread extends Thread{
        @Override
        public void run()
        {
            boolean resume= true;
            while(resume)
            if (System.currentTimeMillis() > lastKeyPressed+400)
            {
                String text = jTextField1.getText();
                if (text.equals(""))
                    dbHandler.useQuery(null);
                else
                    dbHandler.search(text, true, true, true, true, false);
                resume=false;
            } else {
                try {
                    Thread.sleep(System.currentTimeMillis() - lastKeyPressed+501);
                } catch (InterruptedException ex) {
                    resume=false;
                }
            }

        }
    }

    int count = 0;
    /*public void parseStatus(String line)
    {
        count++;
        if (count <=25 )
        {
            return;
        }
        count=0;
        float currentTime;
        float maxTime;

        String[] parts=line.split(" +");
        //System.out.println(Arrays.toString(parts));
        currentTime = Float.parseFloat(parts[1]);

        maxTime = Float.parseFloat(parts[4]);
        //TODO do the following only on start of song, performance!
        jSlider1.setMaximum((int) (maxTime*100) );
        
        if(!mousePressedOnSlider1)
            jSlider1.setValue((int) Math.ceil((currentTime*100)));
        
        jSlider1.setMajorTickSpacing((int)(maxTime*10));
        jSlider1.setMinorTickSpacing((int)(maxTime*1));
        //position.setText(parts[2].substring(1,parts[2].length()-3));
        position.setText(secondsToString(parts[1]));
        //duration.setText(parts[5].substring(1,parts[5].length()-3));
        duration.setText(secondsToString(parts[4]));
        //System.out.println(Arrays.toString(parts));


    }*/
    public static String secondsToString(String secs){
        int time = Integer.parseInt(secs.substring(0,secs.length()-2));
        //int tsecs = Integer.parseInt(secs.substring(secs.length()-1,secs.length()));
        int seconds = (int)(time % 60);
        int minutes = (int)((time/60) % 60);
        //int hours = (int)((time/3600) % 24);
        String secondsStr = (seconds<10 ? "0" : "")+ seconds;
        String minutesStr = (minutes<10 ? "0" : "")+ minutes;
        //String hoursStr = (hours<10 ? "0" : "")+ hours;

        //return new String(minutesStr + ":" + secondsStr + "." + tsecs);
        return new String(minutesStr + ":" + secondsStr);
  }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel duration;
    private javax.swing.JButton jButton2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField jTextField1;
    protected javax.swing.JTable mainList;
    private javax.swing.JButton nextButton;
    private javax.swing.JList playLists;
    private javax.swing.JButton playPauseButton;
    private javax.swing.JLabel position;
    private javax.swing.JCheckBox shuffleCheck;
    private javax.swing.JLabel songtitle;
    // End of variables declaration//GEN-END:variables
    private void startSliderThread() {
        if(sliderThread!=null){
            sliderThread.run=false;
            sliderThread.interrupt();
        }
        sliderThread=new SliderThread();
        sliderThread.start();
    }

    public void run() {
        initComponents();
        this.main=Main.getInstance();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //mainList.setModel(dbHandler);
        //dbHandler.fireTableDataChanged();
        setTitle("JAmp codename tunestester pre-beta Library Window");
        songtitle.setAlignmentX(CENTER_ALIGNMENT);
        
        try {
            pauseIcon = new ImageIcon(ImageIO.read(Main.class.getResourceAsStream("/icons/PauseDisabled.png")));
            playIcon = new ImageIcon(ImageIO.read(Main.class.getResourceAsStream("/icons/Play1Hot.png")));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        
        playPauseButtonPlaying(false);
        
        mainList.setRowSorter(dbHandler.sorter);
        mainList.setTransferHandler(new ListTransferHandler());
        //dropTarget = new DropTarget(mainList, DnDConstants.ACTION_MOVE, this);
        
        setVisible(true);
        

        this.addWindowListener(new WindowListener() {

            public void windowOpened(WindowEvent e) {
            }

            public void windowClosing(WindowEvent e) {
                exit();
            }

            public void windowClosed(WindowEvent e) {

            }

            public void windowIconified(WindowEvent e) {
            }

            public void windowDeiconified(WindowEvent e) {
            }

            public void windowActivated(WindowEvent e) {
            }

            public void windowDeactivated(WindowEvent e) {
            }
        });
        
        main.eventReporter.addListener(new JAmpEventListener() {
            public void handleEvent(JAmpEvent event) {
                switch (event.getType()){
                    case SONG:
                        switch(event.getEventID()){
                            case JAmpSongEvent.SONG_STARTED:
                                jSlider1.setValue(0);
                                sliderThread.active=true;
                                synchronized(sliderThread){
                                    sliderThread.notify();
                                }
                                break;
                            case JAmpSongEvent.SONG_ENDED:
                                jSlider1.setValue(0);
                                sliderThread.active=false;
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        startSliderThread();

    }

    public void exit()
    {
        main.exit();

        super.dispose();
    }

    private class SliderThread extends Thread {

        boolean run = true;
        boolean active=false;

        @Override
        public void run() {
            while (run) {
                if(active) {
                    if(!jSlider1.getValueIsAdjusting()){
                        jSlider1.setMaximum((int)(Main.getInstance().getPlayer().getDuration())/100);
                        jSlider1.setValue((int)(Main.getInstance().getPlayer().getPosition()/100));
                        jSlider1.setMajorTickSpacing((int)(Main.getInstance().getPlayer().getDuration())/1000);
                        jSlider1.setMinorTickSpacing((int)(Main.getInstance().getPlayer().getDuration())/5000);
                        position.setText(Long.toString(Main.getInstance().getPlayer().getPosition()/1000));
                        duration.setText(Long.toString(Main.getInstance().getPlayer().getDuration()/1000));
                    }
                } else {
                    synchronized(this) {
                        try {
                            wait();
                        } catch (InterruptedException ex) {}
                    }
                }
                try {
                    sleep(200);
                } catch (InterruptedException ex) {
                }
            }
        }
    }

}
